//
//  Hls.swift
//  Aria2Proxy
//
//  Created by 张宇飞 on 2024/11/5.
//

import Foundation
import M3U8Decoder

struct HLSPlaylist: Decodable {
    let segments: [MediaSegment]
}

private func makeFullPath(url: String, baseUrl: String, host: String) -> String
{
    if url.starts(with: "http") {
        return url
    }

    if url.starts(with: "/") {
        return host + url
    }

    return baseUrl + url
}

final class HLS {
    let url: String
    private let playlist: HLSPlaylist
    private var _duration: Double = 0.0

    var duration: Double {
        return _duration
    }

    init(url: String) async throws {
        let u = URL(string: url)
        self.playlist = try await M3U8Decoder().decode(
            HLSPlaylist.self, from: u!)
        self.url = url
        // 计算时长
        for s in playlist.segments {
            self._duration += s.extinf.duration
        }
    }

    func files() -> [String] {
        // 先 .m3u8 再 key 文件，最后列表
        var ret: [String] = [self.url]
        // 计算 key
        let u = URL(string: self.url)!
        let baseUrl = u.deletingLastPathComponent().absoluteString
        let host = [u.scheme!, "://", u.host()!].joined()

        if let key = self.playlist.segments.first?.ext_x_key {
            ret.append(makeFullPath(url: key.uri, baseUrl: baseUrl, host: host))
        }
        // 添加文件列表
        for s in self.playlist.segments {
            ret.append(makeFullPath(url: s.uri, baseUrl: baseUrl, host: host))
        }
        return ret
    }
}
